from django.http import HttpResponse
from django.shortcuts import render_to_response
#from ragendja.template import render_to_response
from django.template import RequestContext
from django.contrib.auth.models import User,AnonymousUser
from django.core.paginator import Paginator, InvalidPage, EmptyPage

from realpython.guestbook.models import GuestBook
from realpython.guestbook.forms import GuestBookForm, GuestBookFormForAnonymousUser
from realpython.index.functions import *

def index(request):
    sendmsg = False
    form = createForm(request)
    if request.method == 'POST':
        if form.is_valid():
            sendmsg = True
            topic = form.cleaned_data['topic']
            message = form.cleaned_data['message']
            if request.user.is_authenticated():
                sender = request.user
                email = None
            else:
                email = form.cleaned_data['email']
                sender = None
                
            newmessage = GuestBook.create(message, topic, sender, email)
            create_message(request, 'Thanks for posting message!')
            request.POST = None
            form = createForm(request)
        else:
            create_message(request, 'ERROR  posting message!', 'error')
    messages = GuestBook.get_all()
    paginator = Paginator(messages, 10)
    p = paginator.page(request.GET.get('page', '1'))
    
    
    temvar = {'form': form, 'sendmsg': sendmsg, 'pager': p}
    return render_to_response('guestbook.html', temvar, context_instance=RequestContext(request))
    
def createForm(request):
    if request.method == 'POST':
        post = request.POST
    else:
        post = None
        
    if request.user.is_authenticated():
        form = GuestBookForm(post)
    else:
        form = GuestBookFormForAnonymousUser(post)
    return form
    
